from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from bike.models import CollegeUser


class Command(BaseCommand):
    help = '创建学院管理员用户'

    def add_arguments(self, parser):
        parser.add_argument('--username', type=str, help='用户名')
        parser.add_argument('--password', type=str, help='密码')
        parser.add_argument('--college', type=str, help='学院代码')
        parser.add_argument('--admin', action='store_true', help='是否为管理员')
        parser.add_argument('--super-admin', action='store_true', help='是否为超级管理员')

    def handle(self, *args, **options):
        username = options['username']
        password = options['password']
        college = options['college']
        is_admin = options['admin']
        is_super_admin = options['super_admin']

        if not all([username, password, college]):
            self.stdout.write(
                self.style.ERROR('请提供用户名、密码和学院代码')
            )
            return

        # 检查学院代码是否有效
        valid_colleges = [choice[0] for choice in CollegeUser._meta.get_field('college').choices]
        if college not in valid_colleges:
            self.stdout.write(
                self.style.ERROR(f'无效的学院代码: {college}')
            )
            self.stdout.write('有效的学院代码:')
            for code, name in CollegeUser._meta.get_field('college').choices:
                self.stdout.write(f'  {code}: {name}')
            return

        # 创建用户
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                email=f'{username}@example.com'
            )
            
            # 创建学院用户
            college_user = CollegeUser.objects.create(
                user=user,
                college=college,
                is_admin=is_admin,
                is_super_admin=is_super_admin
            )
            
            self.stdout.write(
                self.style.SUCCESS(
                    f'成功创建学院用户: {username} ({college_user.get_college_display()})'
                )
            )
            
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'创建用户失败: {e}')
            )
